import * as $http from '@/utlis/interface/orderDlatils'
import { getLocation } from '@/utlis/uni_api'
// import { transformFromWGSToGCJ } from "@/utlis/WSCoordinate"
import { reactive, ref, } from 'vue'
import { useStore, NewOrder } from '@/Pinia/index'
import * as $httphome from "@/utlis/interface/home";
import { riderLocationCache } from "@/Pinia";


export default (proxy: any, Emit: any, Props: any) => {
    const isCommitConfirm = ref(false)
    let lastLatitude: number | undefined = 0
    let lastLongitude: number | undefined = 0
    const nowstatus = useStore()
    const butChange = reactive<any>({
        title: '抢单',
        btn_disable: true,
        data: {
            riderLongitude: null,
            riderLatitude: null,
            orderId: 0
        }
    })
    const NewOrders = NewOrder();
    const locationCacheObj = riderLocationCache();

    //外卖抢单
    const makeOrder = (list: any, index: number) => {
        console.log(1111);

        if (nowstatus.infoData.userRealNameStatus === 1) {
            // index下标 去判断当前是订单数据的哪一个
            let id = list[index].id
            if (list[index].btn_disable) {
                $http.makeOrder(id, proxy)
                    .then((res: any) => {
                        if (res.code == 0) {
                            proxy.$API(proxy).Toast(res.msg, 'success')
                            setTimeout(() => {
                                //待取货
                                Emit('changeTab', { index: 1 });
                                //与下面方法重复
                                //Emit('makeOrder')
                            }, 1000)
                            getNewOrder();
                        }
                    })
                    .catch((err: any) => {
                        proxy.$API(proxy).Toast(err.msg, 'error')
                    })
            }
        } else {

            Emit('setSkipModel')
        }
    }

    //跑腿抢单
    const makeOrder2 = (id: number | string, index: number) => {

        if (nowstatus.infoData.userRealNameStatus === 1) {
            let data = ''
            $http.runErrandsMakeOrder(data, id, proxy).then((res: any) => {
                if (res.code == 0) {
                    proxy.$API(proxy).Toast(res.msg, 'success')


                    setTimeout(() => {
                        // Emit('makeOrder')
                        //待取货
                        Emit('changeTab', { index: 1 });
                        getNewOrder();
                    }, 1000)
                }
            }).catch((err: any) => {
                proxy.$API(proxy).Toast(err.msg, 'success')
            })
        } else {
            Emit('setSkipModel')
        }
    }

    //  打电话联系
    const callPhone = (phone: string) => {
        if (phone) {
            uni.makePhoneCall({
                phoneNumber: phone,
            })
        }
    }

    let itemId: string | number = ""

    //外卖 我已取货或者确认到店
    const takeGoods = async (id: string | number, riderClientStatus: any) => {
        onLocationChangeListener()
        if (nowstatus.infoData.userRealNameStatus === 0) Emit('setSkipModel')
        if (riderClientStatus == 1 || riderClientStatus == 7) {// 1 待取货 7 确认到店
            $http.takeGoods(id, '', proxy).then((res: any) => {
                if (res.code == 0) {
                    proxy.$API(proxy).Toast(res.msg, 'success')
                    console.log("res = " + JSON.stringify(res) + ",riderClientStatus = " + riderClientStatus)
                    setTimeout(() => {
                        if (riderClientStatus == 7) {//确认到店
                            // if (riderClientStatus == 5) {//已取货
                            //配送中
                            Emit('changeTab', { index: 2 });
                        } else {
                            Emit('makeOrder')
                        }
                    }, 1000)
                }
            }).catch((err: any) => {
                return proxy.$API(proxy).Toast(err.msg, 'error')
            })
            // 商品确认送达
        } else if (riderClientStatus == 5) {
            isCommitConfirm.value = true
            itemId = id
        }
    }

    //跑腿
    const takeGoods2 = (id: string | number, currentStatus: number, riderDo: number | string) => {
        let data = { id, riderDo }
        let takeInfo = {
            pickCode: null,
            orderId: id,
            riderLongitude: uni.getStorageSync('riderLongitude'),
            riderLatitude: uni.getStorageSync('riderLatitude'),
        }

        if (nowstatus.infoData.userRealNameStatus === 1) {
            // switch (currentStatus) {
            //     case 3:
            //         Emit('setSendCodeModel', data)
            //         break
            //     case 4:
            //         Emit('setSendCodeModel', data)
            //         break
            //     case 5:
            //         Emit('setSendCodeModel', data)
            //         break
            //     default:
            Emit('setSendCodeModel', data)


            setTimeout(() => {
                Emit('makeOrder')
            }, 1000)


            // $http.runErrandReceviedGoods(takeInfo, proxy).then((res : any) => {
            //     if (res.code == 0) {
            //         proxy.$API(proxy).Toast(res.msg, 'success')
            //         setTimeout(() => {
            //             Emit('makeOrder')
            //         }, 1000)
            //     }
            // }).catch((err : any) => {
            //     proxy.$API(proxy).Toast(err.msg, 'waring')
            // })

            // }

        } else {
            Emit('setSkipModel')
        }
    }

    /**
     * 位置发生变化的监听回调
     */
    const onLocationChangeListener = () => {
        //开启接收位置更新
        uni.startLocationUpdate({
            success: res => {
                console.log('开启接收位置消息成功' + JSON.stringify(res))
                //监听位置变化
                uni.onLocationChange(function (res: any) {
                    //更新经纬度，位置监听回调判断使用
                    lastLatitude = res.latitude
                    lastLongitude = res.longitude
                });
            },
            fail: err => {
                console.error('开启接收位置消息失败：', err)
            },
        });
    }

    //取消变化位置监听
    const onLocationCancelChangeListener = () => {
        //关闭时卸载位置更新监听
        uni.stopLocationUpdate({
            success: (res: any) => {
                console.log('关闭接收位置消息成功' + JSON.stringify(res))
            },
            fail: (err: any) => {
                console.error('关闭接收位置消息失败：', err)
            },
        });
    }
    //更新外卖跑腿订单数量
    const getNewOrder = () => {


        let dateTimes = new Date().getTime()
        $httphome.queryNewOrdersReuqest({ 'time': dateTimes }, proxy).then((res: any) => {
            dateTimes = res.data.time
            NewOrders.NewOrders.order0 = res.data.order0
            NewOrders.NewOrders.order1 = res.data.order1
        })
    }
    const onCancelClick = () => {
        // 处理取消逻辑
        isCommitConfirm.value = false
    }
    //自提订单点击确认
    const onCommitClick = () => {

        isCommitConfirm.value = false
        if (nowstatus.infoData.userRealNameStatus === 0) Emit('setSkipModel')
        uni.showLoading()
        let lat1 = locationCacheObj.locationCacheObj.lat
        let lon1 = locationCacheObj.locationCacheObj.lon
        let data = {
            riderLongitude: lon1,
            riderLatitude: lat1,
            orderId: itemId
        }
        $http.delivered(data, proxy).then((res: any) => {
            if (res.code == 0) {
                proxy.$API(proxy).Toast(res.msg, 'success')
                setTimeout(() => {
                    Emit('makeOrder')
                }, 1000)
            }

            onLocationCancelChangeListener()
        }).catch((err: any) => {
            return proxy.$API(proxy).Toast(err.msg, 'error')
        })
    }

    //外卖 显示转单按钮弹出层
    const clickIsShow = (item: any) => {

        if (item.riderClientStatus == 1) {


            Emit('clickIsShow', item.id)
        } else {
            // return proxy.$API(proxy).Toast('当前订单不可转单', 'error')
        }
    }

    //跑腿 显示转单按钮弹出层
    const clickIsShow2 = (item: any) => {


        if (item.riderClientStatus == 1 && item.status == 1) {
            Emit('clickIsShow', item.id)
        } else {
            // return 	proxy.$API(proxy).Toast('当前订单不可转单', 'error')
        }
    }

    //外卖 获取通话列表按钮
    const getPhoneList = (item: any) => {
        if (item.riderClientStatus == 4) {
            return
        }

        let obj = {
            type: item.riderClientStatus,
            riderPhone: item.riderPhone,
            orderId: item.id,
            arr: [
                {
                    title: '联系商家',
                    phone: item.merchantMobile,
                    type: "B"
                },
                {
                    title: '联系用户',
                    phone: item.phone,
                    type: "C"
                },
                {
                    title: '注册用户',
                    phone: item.userMobile,
                    type: "C0"
                },
            ]
        }

        Emit('getPhoneList', obj)

    }

    //跑腿 获取通话列表按钮
    const getPhoneList2 = (item: any) => {
        console.log('点击我已取货');

        if (item.riderClientStatus == 4) {
            return
        }

        let obj = {}

        if (item.riderDo == '1') {
            obj = {
                type: item.riderClientStatus,
                riderPhone: item.riderPhone,
                orderId: item.id,
                arr: [{
                    title: '联系收件人',
                    phone: item.receivePhone,
                    type: "C1"
                }, {
                    title: '注册用户',
                    phone: item.userMobile,
                    type: "C0"
                },]
            }
        } else {
            obj = {
                type: item.riderClientStatus,
                riderPhone: item.riderPhone,
                orderId: item.id,
                arr: [
                    {
                        title: '联系发件人',
                        phone: item.pickPhone,
                        type: "C1"
                    },
                    {
                        title: '联系收件人',
                        phone: item.receivePhone,
                        type: "C2"
                    }, {
                        title: '注册用户',
                        phone: item.userMobile,
                        type: "C0"
                    },
                ]
            }
        }

        Emit('getPhoneList', obj)
    }

    return {
        makeOrder,
        makeOrder2,
        butChange,
        callPhone,
        takeGoods,
        takeGoods2,
        isCommitConfirm,
        onCommitClick,
        clickIsShow,
        clickIsShow2,
        getPhoneList,
        getPhoneList2,
        onCancelClick
    }
}
